package eraserhead.xml.response;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import xml.Message;
import client.IMessageHandler;
import eraserhead.boundary.DecisionGUI;
import eraserhead.controller.UserController;
import eraserhead.entity.OpenDecision;
import eraserhead.entity.User;
import eraserhead.xml.XmlNode;

/**
 * Response handler for SignInOpen
 * @author Michael Checca
 */
public class SignInOpenResponse implements IMessageHandler {

	@Override
	public void process(Message response) {
		Node signin = XmlNode.findNode(response.contents, "signInResponse");
		if (signin != null) {
			String id = XmlNode.getAttribute(signin, "id");
			String type = XmlNode.getAttribute(signin, "type");
			String question = XmlNode.getAttribute(signin, "question");
			int numChoices = XmlNode.getAttributeInt(signin, "numChoices");
			int numRounds = XmlNode.getAttributeInt(signin, "numRounds");
			int position = XmlNode.getAttributeInt(signin, "position");
			OpenDecision model = new OpenDecision(numRounds, numChoices);
			model.userJoin(User.getUser());
			model.setUserPlacement(position);
			model.setQuestion(question);
			model.setId(id);
			NodeList choicesNodes = signin.getChildNodes();
			DecisionGUI dg = DecisionGUI.getInstance(model);
			for (int i = 0; i < choicesNodes.getLength(); i++) {
				String value = XmlNode.getAttribute(choicesNodes.item(i), "value");
				int index = XmlNode.getAttributeInt(choicesNodes.item(i), "index");
				model.setChoice(index, value);
				dg.getChoicePanel().setChoiceField(index, value);
			}
			dg.setEventID(id);
			dg.setVisible(true);
			new UserController(model, dg.getChoicePanel()).process();
			System.out.println(String.format("SignInOpenResponse received [id: %s, type: %s, question: %s, numChoices: %d, numRounds: %d, position: %d]",
					id, type, question, numChoices, numRounds, position));
		}
	}
}
